package testsuite;

import static org.junit.Assert.*;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class TestStatement
{
    private static String url = "jdbc:xsqs://localhost";

    private static String query = "/books/book/title";
    
    private static String update = "setDocument(test/book3.xml)";

    private static Statement stmt;

    @BeforeClass
    public static void loadDriver() throws ClassNotFoundException, SQLException
    {
	Class.forName("xsqs.jdbc.DriverImpl");
	stmt = DriverManager.getConnection(url).createStatement();
    }

    @Before
    public void createStatement() throws SQLException
    {
	if (stmt.isClosed() == true)
	{
	    stmt = DriverManager.getConnection(url).createStatement();
	}
    }
    
    @Test(expected = SQLException.class)
    public void testClose() throws SQLException
    {
	stmt.close();
	stmt.clearWarnings();
    }

    @Test
    public void testExecuteString() throws SQLException
    {
	assertTrue(stmt.execute(query));
	assertNotNull(stmt.getResultSet());
	assertFalse(stmt.execute(update));
	assertNull(stmt.getResultSet());
	
	stmt.setQueryTimeout(1);
	assertTrue(stmt.execute(query));
	assertNotNull(stmt.getResultSet());
	assertFalse(stmt.execute(update));
	assertNull(stmt.getResultSet());
    }

    @Test(expected = SQLException.class)
    public void testExecuteQuery() throws SQLException
    {
	assertNotNull(stmt.executeQuery(query));
	assertNull(stmt.getResultSet());
	
	stmt.setQueryTimeout(1);
	assertNotNull(stmt.executeQuery(query));
	assertNull(stmt.getResultSet());
	
	stmt.executeQuery(update);
    }

    @Test
    public void testSetMaxRows() throws SQLException
    {
	stmt.setMaxRows(5);
	ResultSet rs = stmt.executeQuery(query);
	int rsSize = 0;
	while(rs.next())
	{
	    ++rsSize;
	}
	assertEquals(5, rsSize);
    }

    @Test(expected = SQLException.class)
    public void testExecuteUpdateString() throws SQLException
    {
	stmt.executeUpdate(update);
	assertNull(stmt.getResultSet());
	
	stmt.setQueryTimeout(1);
	stmt.executeUpdate(update);
	assertNull(stmt.getResultSet());
	
	stmt.executeUpdate(query);
    }

}
